package com.quan.sdk.weixin.scheduler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mzlion.easyokhttp.HttpClient;
import com.quan.sdk.weixin.constant.API;
import com.quan.sdk.weixin.model.AccessToken;
import com.quan.sdk.weixin.utils.WeixinContext;

/**
 * 定时获取AccessToken
 * @author yhaoquan
 *
 */
@Component
public class AccessTokenRefreshTask {
	
	private static Logger logger = LoggerFactory.getLogger(AccessTokenRefreshTask.class);

	/**
	 * 0/5 * * * * ? 	  每5秒执行一次
	 * 0 55 0/1 * * ?	 每个1小时55分获取一次
	 */
	@Scheduled(cron = "0 55 0/1 * * ?")
	public void accessTokenRefreshJob() {
		//获取AccessToken
		AccessToken accessToken = getAccessToken();
		//保存AccessToken到上下文
		WeixinContext.setAccessToken(accessToken.getAccess_token());
	}
	
	public static AccessToken getAccessToken() {
		AccessToken accessToken = HttpClient.get(API.get(API.ACCESS_TOKEN_URL, WeixinContext.getAppId(), WeixinContext.getAppSecret())).execute().asBean(AccessToken.class) ;
		if(accessToken.getErrcode() > 0) {
			logger.error("微信全局唯一接口调用凭证Access_Token获取[失败]：{}", accessToken.getErrmsg());
		} else {
			logger.info("微信全局唯一接口调用凭证Access_Token获取[成功]:{}", accessToken);
		}
		return accessToken ;
	}
}
